package com.htg.dialog;

import android.app.AlertDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import androidx.collection.ArrayMap;



public class DialogKeyValueTable {

    private Context cxt;

    public DialogKeyValueTable(Context cxt) {
        this.cxt = cxt;
    }

    public void show(ArrayMap<String, String> arrayMap) {
        AlertDialog.Builder builder = new AlertDialog.Builder(cxt);
        AlertDialog alertDialog = builder.create();


        View view = LayoutInflater.from(cxt).inflate(R.layout.dialog_text_items, null);

        ListView listView = view.findViewById(R.id.lv_dialog_text_items);
        Button btCancel = view.findViewById(R.id.bt_dialog_text_items_cancel);
        ItemAdapter itemAdapter = new ItemAdapter(cxt, arrayMap);
        listView.setAdapter(itemAdapter);
        btCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });


        alertDialog.setView(view);
        alertDialog.show();

    }


    private class ItemAdapter extends BaseAdapter {

        private Context context;
        private ArrayMap<String, String> map;

        public ItemAdapter(Context context, ArrayMap<String, String> map) {
            this.context = context;
            this.map = map;
        }

        @Override
        public int getCount() {
            return map.size();
        }

        @Override
        public Object getItem(int i) {
            return map.valueAt(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            Holder holder = null;
            if (view == null) {
                view = LayoutInflater.from(context).inflate(R.layout.dialog_keyvalue, null);
                holder = new Holder();
                holder.tvKey = view.findViewById(R.id.tv_adapter_keyvalue_key);
                holder.tvValue = view.findViewById(R.id.tv_adapter_keyvalue_value);
                view.setTag(holder);
            } else {
                holder = (Holder) view.getTag();
            }
            holder.tvKey.setText(map.keyAt(i));
            holder.tvValue.setText(map.valueAt(i));

            return view;
        }
    }

    class Holder {
        TextView tvKey;
        TextView tvValue;
    }


}
